package com.zhenyi.jiahua.interceptor.app;

import com.cjw.model.DBMap;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.utils.AuthUtils;
import com.utils.HttpUtils;
import com.wxpay.utils.MD5Util;

import cn.hutool.core.util.URLUtil;

public class AppAuthInterceptor implements Interceptor {

	private void renderLogin(Controller controller) {
		// controller.redirect("/jh/app");
		String before = getRequestUrl(controller);
		controller.redirect("/jh/app?state=" + URLUtil.encode(before));
	}

	private String getRequestUrl(Controller controller) {
		String url = controller.getRequest().getRequestURL().toString();
		String queryurl = controller.getRequest().getQueryString();
		if (StrKit.notBlank(queryurl)) {
			url = url + "?" + queryurl;
		}
		return url;
	}

	/**
	 * 校验元
	 * 
	 * @param controller
	 * @return
	 * @Time 2018年11月29日 上午12:06:27
	 */
	private boolean validateOsm(Controller controller) {
		// return HttpUtils.getOS(getRequest());
		// String os = HttpUtils.getOS(controller.getRequest());
		// String osm = MD5Util.MD5Encode(os, "utf-8");
		String oldOsm = controller.getCookie("osm", "");
		if (StrKit.isBlank(oldOsm)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		try {
			if (!validateOsm(controller)) {
				controller.setCookie("osm", "", 0);
				AuthUtils.logout(controller);
				renderLogin(controller);
				return;
			}
			String uid = AuthUtils.getTokenUid(controller);
			if (StrKit.notBlank(uid)) {
				inv.invoke();
			} else {
				renderLogin(controller);
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			DBMap map = new DBMap();
			map.put("status", 500);
			map.put("msg", "出错");
			controller.renderJson(map);
		}
	}

}
